package com.nasarius.bank.scorecard.web.controller.admin;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.nasarius.bank.scorecard.dao.TopicsDAO;
import com.nasarius.bank.scorecard.domain.Topics;
import com.nasarius.bank.vo.TopicsVO;

@Controller
public class TopicDetailsController {
	 /** Logger that is available to subclasses */
	 protected final Log LOG = LogFactory.getLog(getClass());
		@Autowired
		private TopicsDAO topicsDAO;	
		@InitBinder
		protected void initBinder(ServletRequestDataBinder binder) {
				binder.registerCustomEditor(List.class,new CustomCollectionEditor(List.class));
		}		
		/**
		 * For every request for this controller, this will create a topicdetails
		 * instance for the form .
		 */
		@ModelAttribute
		public TopicsVO newRequest(@RequestParam(required = false) String topicID,Model model) {
			TopicsVO topicsVO = new TopicsVO();
			topicsVO.setTopics(topicsDAO.selectAllTopics());
			return topicsVO;
		}
		   /**
	     * <p>Person form request.</p>
	     * 
	     * <p>Expected HTTP GET and request '/topicdetails/view'.</p>
	     */
	    @RequestMapping(value="/topicdetails/view", method=RequestMethod.GET)
	    public void form() {}
	    
	    
	    public void setTopicsDAO(TopicsDAO topicsDAO) {
			this.topicsDAO = topicsDAO;
		}
		/**
	     * <p>Saves a person.</p>
	     * 
	     * <p>Expected HTTP POST and request '/topicdetails/add'.</p>
	     */
	    @RequestMapping(value="/topicdetails/add", method=RequestMethod.POST)
	    public TopicsVO add(TopicsVO topicsVO, Model model) {
	    	LOG.info("Add new factor");
	    	topicsVO.getTopics().add(new Topics());
	    	return topicsVO;
	    }
		@RequestMapping(value="/topicdetails/update", method=RequestMethod.POST)
	    public void update(TopicsVO topicsVO, Model model) {
	    	for(Topics topics:topicsVO.getTopics()){
	    		if(topics.getTopicid()!=null)
	    			topicsDAO.updateTopicsByPrimaryKey(topics);
    			else
    				topicsDAO.insertTopics(topics);
	    	}
	    }
}
